/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.foolishbird.crow.core.util;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 替代common-lang3的RandomStringUtils，因为使用的是new Random()做静态属性，有线程安全问题
 *
 * @author foolish-bird
 */
public class RandomStringUtils {

    /**
     * 数字字符串
     */
    private static final String NUMBER = "0123456789";

    /**
     * 小写字母字符串
     */
    private static final String SMALL_LETTER = "abcdefghijklmnopqrstuvwxyz";

    /**
     * 大写字母字符串
     */
    private static final String CAPITAL_LETTER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 数字字符串+小写字母字符串+大写字母字符串
     */
    private static final String ALL = NUMBER + SMALL_LETTER + CAPITAL_LETTER;

    /**
     * 生成有限位数的数字随机字符串
     *
     * @param randomNum 随机位数
     * @return 随机字符串
     */
    public static String randomNumber(int randomNum) {
        StringBuilder random = new StringBuilder();
        for (int i = 0; i < randomNum; i++) {
            random.append(ThreadLocalRandom.current().nextInt(10));
        }
        return random.toString();
    }

    /**
     * 小写字符串随机
     *
     * @param randomNum 随机树位数
     * @return 随机字符串
     */
    public static String randomSmallLetter(int randomNum) {
        return random(randomNum, SMALL_LETTER.toCharArray());
    }

    /**
     * 小写字符串随机
     *
     * @param randomNum 随机树位数
     * @return 随机字符串
     */
    public static String randomCapitalLetter(int randomNum) {
        return random(randomNum, SMALL_LETTER.toCharArray());
    }

    /**
     * 数字+大写字符串+小写字符串随机
     *
     * @param randomNum 随机树位数
     * @return 随机字符串
     */
    public static String randomAll(int randomNum) {
        return random(randomNum, ALL.toCharArray());
    }

    /**
     *
     * @param randomNum
     * @param chars
     * @return
     */
    private static String random(int randomNum, char[] chars) {
        StringBuilder random = new StringBuilder();
        for (int i = 0; i < randomNum; i++) {
            int index = ThreadLocalRandom.current().nextInt(chars.length);
            random.append(chars[index]);
        }
        return random.toString();
    }

}
